#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/stat.h>
#include <linux/watchdog.h>

#define msleep(ms) usleep(ms*1000)

#define	WATCHDOG_IOCTL_BASE	'W'
#define	WDIOC_RESTORE        _IOR(WATCHDOG_IOCTL_BASE, 8, int)
#define	WDIOC_SETOPTIONS	_IOR(WATCHDOG_IOCTL_BASE, 4, int)
#define	WDIOC_SETTIMEOUT        _IOWR(WATCHDOG_IOCTL_BASE, 6, int)

int fd;

static void *WatchDog_Thread(void * pParam)
{
	int timeout = 30;  //WatchDog Timeout 时间:30秒
	int WatchdogFd = -1;
	int new_options;
	
	printf("***************************PID: %d --->WatchDog()\n", getpid());

	WatchdogFd = open("/dev/watchdog",O_WRONLY);
	if(WatchdogFd == -1)
	{
		printf("---ERROR: Open WatchDog Device Failed!\n");
		return 0;
	}

	fd = WatchdogFd;

	// Set WatchDog Timeout
	ioctl(WatchdogFd, WDIOC_SETTIMEOUT, &timeout);

	/* set WatchDog enable */
	new_options = WDIOS_ENABLECARD;
	ioctl(WatchdogFd, WDIOC_SETOPTIONS, &new_options);

	// Feed WatchDog First Time
	write(WatchdogFd, "\0", 1);	

	while(1)
	{
		// Feed WatchDog
		if(WatchdogFd != -1)
		{
			write(WatchdogFd, "\0", 1);
		}
		msleep(2000);
	}
	return 0;
}

void re_wdt()
{
	int on;

	on = 1;
	//ioctl(fd, WDIOC_SETTIMEOUT, &on);

	//ioctl(dev, WDIOC_RESTORE);
	//ioctl(fd, WDIOC_SETOPTIONS);
}

int run()
{
	while(1) {
		printf("run.....\n");
		msleep(1500);
		re_wdt();
	}
}

int main()
{
	printf("*****************PID: %d --->main()\n", getpid());

	// Start Watch Dog Thread
	//定时(30秒)向硬件WatchDog发数据
	pthread_t WatchDogThreadId = 0;
	pthread_create(&WatchDogThreadId, NULL, WatchDog_Thread, NULL);	

	run();
	msleep(1500);


	//此程序一直在等待WatchDogThreadId的结束
	void *ptr;
	pthread_join(WatchDogThreadId, &ptr);
	exit(0);
}

